﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using Oraycn.MPlayer;
using Oraycn.MCapture;
using System.Drawing.Drawing2D;
using MySql.Data.MySqlClient;
using System.IO;
using System.Linq;
using System.Numerics;
using MDT.NetLibHantek;

namespace spaceVibration
{
    public partial class Form1 : Form
    {
        //五秒FFT相加，FFT
        public static Queue<float[]> FFTQueue = new Queue<float[]>();

        //同步示波器配置
        private ManagedHTMarch m_hantek = new ManagedHTMarch(0);
        private ManagedHTMarch.THantekTrigSweep m_trigSweep;
        private short[] m_calLevel = new short[32];
        private int m_risingEdge = 0;
        private int m_fallingEdge = 0;
        private double m_lastVoltage = 0;
        public static double[] analogValues;
        public static uint trigPoint = 0;
        public static bool oneDrawAmpFlag = false;//用作画时域图标志位
        //同步示波器配置结束

        public static bool audioGetFlag = false;
        public static bool oneaudioGetFlag = false;
        public static bool isGetOTDR = false;

        TcpListener server;
        NetworkStream stream;
        public static IAudioPlayer audioPlayer;
        public IMicrophoneCapturer microphoneCapturer;


        public String wavpath = "";

        //引用DSP函数类
        static DspFunction dF = new DspFunction();
        public string clientIp;
        public int port;
        public int clientport = 0;
        //System.Timers.Timer timer = null;
        public int dLength;
        byte[] Signalbyte;
        public static int[] SingalUint;
        public static Queue<int[]> singalQueue = new Queue<int[]>();
        public static float[][] one_SingalUint;
        public static int[] OTDR_ALARM = new int[1600];//CFAR_COLUMN
        wav w = new wav();
        int flag;
        public String bofangpath;
        private ConfigClass cf;
        private int unit;
        public int freq;
        private bool isConFlag = false;
        //private bool insertFFTdataFlag_channel1 = false;//

        //配置
        int channel = 5;//通道数
        int samplingRate = 2048;//采样频率
        int showChannel = 3;//显示点个数
        int n = 1;//每秒的音频数据切割成n段，防止画图卡顿问题
        //int oneLength = 2048;//单片长度，与FFT方法中的FFT_N变量对应，数据分段后不够的，将原有数据复制四份填充
        int oneLength = 4096;
        //int oneLength = 128;.
        double fre_boundary = 500;//检测最大频率值

        //计算能量值
        public static float lightStrength;
        public static double caAmp;

        //初始化数据
        public List<float> x = new List<float>();
        public List<float> y1 = new List<float>();
        public List<float> y2 = new List<float>();
        public List<float> y3 = new List<float>();
        float y1_max = 0;
        float y2_max = 0;
        float y3_max = 0;
        //将五秒的最终确定频率存在队列
        public Queue<float[]> frequency1 = new Queue<float[]>();
        public Queue<float[]> frequency2 = new Queue<float[]>();
        public Queue<float[]> frequency3 = new Queue<float[]>();
        string amp1_json;
        string amp2_json;
        string amp3_json;
        bool amp1_flag = false;
        bool amp2_flag = false;
        bool amp3_flag = false;

        //用作画能量图
        int[] ampData;
        public List<float> y_amp = new List<float>();
        public List<float> x_amp = new List<float>();
        public List<float> y_0_amp = new List<float>();//零线

        //修正参数，由于下位机上传的是2000hz，而此次计算按着2048计算，因此fft后的对应频率应该除以1.024
        double revise = 1.024;

        //fft初始化配置
        FFT wavFFT = new FFT();
        private double interval;
        private int num;
        private double run_time = 0;//系统运行时间.

        public Form1()
        {
            InitializeComponent();
            initconfig();

            Oraycn.MPlayer.GlobalUtil.SetAuthorizedUser("lijianbin", "ljb0824");
            //Form1.audioPlayer = PlayerFactory.CreateAudioPlayer(3, 10000, 1, 16, 10);
            Form1.audioPlayer = PlayerFactory.CreateAudioPlayer(3, 2000, 1, 16, 10);

            Thread thCon = new Thread(checkCon);
            thCon.IsBackground = true;
            thCon.Start();

            server = new TcpListener(System.Net.IPAddress.Any, this.port);
            server.ExclusiveAddressUse = false;
            server.Start();

            Thread thGetVoice = new Thread(getVoice);
            thGetVoice.IsBackground = true;
            thGetVoice.Start();

            Thread thBuffer = new Thread(getBuffer);
            thBuffer.IsBackground = true;
            thBuffer.Start();

            Thread thDeleteDataExpire = new Thread(deleteDataExpire);
            thDeleteDataExpire.IsBackground = true;
            thDeleteDataExpire.Start();

            //Thread InsertOrigin = new Thread(InsertOriginData);
            //InsertOrigin.IsBackground = true;
            //InsertOrigin.Start();

            //Thread InsertFFTChannel1 = new Thread(InsertFFTData1);
            //InsertFFTChannel1.IsBackground = true;
            //InsertFFTChannel1.Start();

            //Thread InsertFFTChannel2 = new Thread(InsertFFTData2);
            //InsertFFTChannel2.IsBackground = true;
            //InsertFFTChannel2.Start();

            //Thread InsertFFTChannel3 = new Thread(InsertFFTData3);
            //InsertFFTChannel3.IsBackground = true;
            //InsertFFTChannel3.Start();

            //虚拟示波器调档校验
            m_hantek.SetTimeDivision();
            m_calLevel = m_hantek.GetCalibrationLevel();
            m_hantek.SetCalibrationLevel(m_calLevel);

            zGraph2.m_SySnameY = "强度（V）";
            zGraph2.m_SySnameX = "时间（ms）";
            //开一个线程用作虚拟示波器取数据
            Thread hantek = new Thread(getHantekData);
            hantek.IsBackground = true;
            hantek.Start();

            ///画矩形条
            this.Focus();
            x.Clear();
            y1.Clear();
            y2.Clear();
            y3.Clear();

            x_amp.Clear();
            
            //为适应航天项目1-50hz范围，只显示1-50hz
            interval = 1.0 / Droplet.DropFFT.keepTime;
            num = (int)(fre_boundary / interval);
            double n = 0;
            for (int i = 0; i < num; i++)
            {
                //未做1.024修正
                n = n + interval;
                x.Add((float)n);
                y1.Add(0);
            }
            for (int i = 0; i < 1000; i++)
            {
                x_amp.Add(i * 2);
                y_amp.Add(0);
                y_0_amp.Add(0);
            }

            timerDrawZGraphAmp.Start();

            zGraph1.f_ClearAllPix();
            zGraph1.f_reXY();
            //zGraph1.f_AddPix(ref x, ref y1, Color.FromArgb(0, 128, 192), 12, LineJoin.MiterClipped, LineCap.NoAnchor, ZhengJuyin.UI.ZGraph.DrawStyle.bar);
            zGraph1.f_AddPix(ref x, ref y1, Color.FromArgb(0, 128, 192), 2);
            zGraph1.f_Refresh();

            //通道2画图初始化
            zGraph2.f_ClearAllPix();
            zGraph2.f_reXY();
            zGraph2.f_AddPix(ref x_amp, ref y_amp, Color.Yellow, 4);
            zGraph2.f_AddPix(ref x_amp, ref y_0_amp, Color.Red, 4);
            zGraph2.f_Refresh();

            button1.Enabled = true;
            timerDrawZGraph.Start();

            //连接dsp
            flag = 0;   //停止声音采集；
            if (dF.client == null)
            {
                dF.client = server.AcceptTcpClient();// 等待客户端TCP连接 [会阻塞线程]
                dF.stream = dF.client.GetStream();//获取网络流
                stream = dF.stream;
                clientIp = ((IPEndPoint)dF.client.Client.RemoteEndPoint).Address.ToString();
                clientport = ((IPEndPoint)dF.client.Client.RemoteEndPoint).Port;
            }

            if (dF.client.Connected)
            {
                Console.WriteLine("TCP连接成功");
                dspStatusLabel.Text = "TCP连接成功";
                byte[] recvACK = new byte[20];
                int ret = stream.Read(recvACK, 0, 20);
                Thread.Sleep(1000);
                if (dF.DevOpen(0, clientIp, port) == true)
                {
                    dspStatusLabel.Text = "DSP连接";
                    //第一点调距
                    //if (dF.DevWritSpecial(0, dF.NETCMD_SPECIAL_NAME_SINGLECOL_1, 104))
                    if (dF.DevWritSpecial(0, dF.NETCMD_SPECIAL_NAME_SINGLECOL_1, 104))
                        Console.WriteLine("调距成功");
                    else
                        Console.WriteLine("调距失败");

                    //第二点调距
                    if (dF.DevWritSpecial(0, dF.NETCMD_SPECIAL_NAME_SINGLECOL_2, 102))
                        Console.WriteLine("调距成功");
                    else
                        Console.WriteLine("调距失败");


                    //第三点调距
                    if (dF.DevWritSpecial(0, dF.NETCMD_SPECIAL_NAME_SINGLECOL_3, 103))
                        Console.WriteLine("调距成功");
                    else
                        Console.WriteLine("调距失败");
                }
                else
                {
                    dspStatusLabel.Text = "DSP断开";
                }
            }

            //cbxVoltDiv.Items.AddRange(Enum.GetNames(typeof(ManagedHTMarch.THantekVoltDivision)));
            //cbxVoltDiv.SelectedItem = ManagedHTMarch.THantekVoltDivision._2V.ToString();

            //cbxTimeDiv.Items.AddRange(Enum.GetNames(typeof(ManagedHTMarch.THantekTimeDivision)));
            //cbxTimeDiv.SelectedItem = ManagedHTMarch.THantekTimeDivision._200MS.ToString();

            //cbxTrigSweep.Items.AddRange(Enum.GetNames(typeof(ManagedHTMarch.THantekTrigSweep)));
            //cbxTrigSweep.SelectedItem = ManagedHTMarch.THantekTrigSweep.Auto.ToString();
        }

        private void InsertFFTData1()
        {
            while (true)
            {
                if (!amp1_flag) continue;
                amp1_flag = false;
                double time = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000;
                MySqlConnection conn = new MySqlConnection(mysql.mysqlConnectionString);
                conn.Open();
                mysql.InsertFFTData(conn,n, amp1_json, 1, time, samplingRate, oneLength);
                Thread.Sleep(150);
            }
        }

        private void InsertFFTData2()
        {
            while (true)
            {
                if (!amp2_flag) continue;
                amp2_flag = false;
                double time = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000;
                MySqlConnection conn = new MySqlConnection(mysql.mysqlConnectionString);
                conn.Open();
                mysql.InsertFFTData(conn, n, amp2_json, 2, time, samplingRate, oneLength);
                Thread.Sleep(150);
            }
        }

        private void InsertFFTData3()
        {
            while (true)
            {
                if (!amp3_flag) continue;
                amp3_flag = false;
                double time = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000;
                MySqlConnection conn = new MySqlConnection(mysql.mysqlConnectionString);
                conn.Open();
                mysql.InsertFFTData(conn, n, amp3_json, 3, time, samplingRate, oneLength);
                Thread.Sleep(150);
            }
        }

        //private void InsertOriginData()
        //{
        //    while (true)
        //    {
        //        if (DspFunction.insertOriginDataFlag == 0) continue;
        //        if (DspFunction.insertOriginDataFlag != 1) continue;
        //        DspFunction.insertOriginDataFlag++;//最后要是用次数计算存储数据次数，记住要减一，此处为避免多次存数据库
        //        mysql.InsertOriginData(samplingRate, DspFunction.ph, DspFunction.timeNow);
        //        Thread.Sleep(1024);
        //    }
        //}

        private void button1_Click_1(object sender, EventArgs e)
        {
            Console.WriteLine("connecttcp_Click");
            isConFlag = true;
            flag = 1;   //开始获取声音
            dspStatusLabel.Text = "开始获取数据";
            button2.Enabled = true;
            button1.Enabled = false;
            timer_run_time.Start();
        }

        public void initconfig()
        {
            cf = new ConfigClass("config.ini");
            this.port = int.Parse(cf.IniReadValue("DPM", "DPMPORT")[0]);
            this.wavpath = cf.IniReadValue("DPM", "WAVPATH")[0];
            this.dLength = int.Parse(cf.IniReadValue("DPM", "LEN")[0]);
            this.unit = int.Parse(cf.IniReadValue("DPM", "UNIT")[0]);
            this.freq = int.Parse(cf.IniReadValue("DPM", "FREQ")[0]);

        }

        private void checkCon()
        {
            int count = 0;
            while (true)
            {
                count++;
                if (isConFlag && flag == 0)
                {
                    if (!dF.DevHeartBeatReceive())
                    {
                        if (count > 20)
                        {
                            flag = 0;

                            if (dF.client.Connected)
                            {
                                Console.WriteLine("TCP连接成功");
                                dspStatusLabel.Text = "TCP连接成功";
                                byte[] recvACK = new byte[20];
                                int ret = stream.Read(recvACK, 0, 20);
                                Thread.Sleep(1000);
                                if (dF.DevOpen(0, clientIp, port) == true)
                                    dspStatusLabel.Text = "DSP连接";
                                else
                                    dspStatusLabel.Text = "DSP断开";
                            }
                        }
                    }
                    else
                    {
                        count = 0;
                    }
                }
                Thread.Sleep(1000);
            }
        }

        void getVoice()
        {
            int dur_millsecond = 0;
            Console.WriteLine("getVoice");
            while (true)
            {
                if (flag == 1)
                {
                    y1_max = 0;
                    y2_max = 0;
                    y3_max = 0;

                    DateTime t_begin = DateTime.Now;
                    byte[] temp_bs = null;
                    if (dF.DevSignalCol(0, ref SingalUint, ref Signalbyte, ref dLength))
                    {
                        temp_bs = Signalbyte;
                        Signalbyte = Droplet.DropFFT.VoiceYuanSheng(Signalbyte, channel);
                        Droplet.DropFFT.GuiyiWave(ref SingalUint, Signalbyte);
                        Signalbyte = temp_bs;
                        int c_len = Signalbyte.Length;
                        byte[] playData = new byte[c_len / 5];
                        Array.Copy(Signalbyte,0, playData,0, c_len / 5);
                        Console.WriteLine(Signalbyte.Length);
                        //Form1.audioPlayer.Play(playData);//播放声音
                        audioGetFlag = true;
                        //Console.WriteLine("读取正确" + Convert.ToString(sumlength / 2));
                        Console.WriteLine("读取正确");
                    }
                    else
                    {
                        Console.WriteLine("读取错误");
                        Thread.Sleep(1000);
                    }
                    DateTime t_end = DateTime.Now;
                    dur_millsecond = t_end.Subtract(t_begin).Milliseconds;

                }

                Thread.Sleep(1024 - dur_millsecond);
            }
        }

        private void getBuffer()
        {
            while (true)
            {
                if (!audioGetFlag) { Thread.Sleep(1); continue; }
                audioGetFlag = false;
                float[][] channelsDateArr = new float[showChannel][];//将本次每个要显示的通道存入数组
                int samplintRate_set = SingalUint.Length / channel;
                for (int ii = 0; ii < showChannel; ii++)
                {
                    channelsDateArr[ii] = new float[samplintRate_set];
                    Array.Copy(SingalUint, ii * samplintRate_set, channelsDateArr[ii], 0, samplintRate_set);//给每个要显示通道添加数据
                }
                double one_len = samplintRate_set / n;
                double needFeedNum = oneLength / one_len;
                //Console.WriteLine(SingalUint.Length);
                //int[] one_SingalUint = new int[one_len];
                //显示通道
                one_SingalUint = new float[showChannel][];
                for (int i = 0; i < n; i++)//分多少段的循环
                {
                    for (int b = 0; b < showChannel; b++)
                    {
                        one_SingalUint[b] = new float[oneLength];
                        //在数据后填充0的方式
                        for (int c = 0; c < needFeedNum; c++)
                        {
                            if (c == 0)
                            {
                                Array.Copy(channelsDateArr[b], i * (int)one_len, one_SingalUint[b], c * (int)one_len, (int)one_len);//凑数据
                            }
                            else
                            {
                                for (int j = 0; j < one_len; j++)
                                {
                                    one_SingalUint[b][c * (int)one_len + j] = 0;
                                }
                            }
                        }
                    }
                    oneaudioGetFlag = true;
                    Thread.Sleep(920 / n);
                }
            }
        }

        private void getHantekData()
        {
            while (true)
            {
                if (oneDrawAmpFlag) { Thread.Sleep(1);continue; }
                uint nReadLine = 1000000;
                short triggerLevel = 10;
                short[] dataCH1 = new short[nReadLine];
                short[] dataCH2 = new short[nReadLine];
                //uint trigPoint = 0;
                m_hantek.ReadHardData(out dataCH1, out dataCH2, nReadLine, m_calLevel, m_trigSweep, ManagedHTMarch.THantekChannelNumber.CH1, triggerLevel, ManagedHTMarch.THantekTriggerSlope.Rise, 10, nReadLine, out trigPoint, ManagedHTMarch.THantekInsertMode.StepDValue);
                analogValues = m_hantek.ConvertReadData(dataCH1);
                oneDrawAmpFlag = true;
            }
        }

        private void timerDrawZGraph_Tick(object sender, EventArgs e)
        {
            float[] samples;
            if (!oneaudioGetFlag) { Thread.Sleep(2); return; }
            //初始化标志位
            oneaudioGetFlag = false;
            //Console.WriteLine("收到数据");
            int one_len = samplingRate / n;
            for (int c = 0; c < one_SingalUint.Length; c++)
            {
                if (one_SingalUint[c].Length == 0)
                    continue;
                samples = new float[oneLength];
                Array.Copy(one_SingalUint[c],samples, oneLength);
                //fft运算,返回512个数据，但256-512都是0，因此遍历只需遍历一半就够了
                //保存fft之前的数据
                //string ph = @"D://fft_pre.txt";
                //FileStream fs = new FileStream(ph, FileMode.Create);//新建文件
                //StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
                //for (int i = 0; i < samples.Length; i++)
                //{
                //    sw.Write(samples[i]);
                //    sw.Write("\r\n");
                //    sw.Flush();
                //}
                //sw.Close();
                wavFFT.calculate(ref samples);
                wavFFT.covertDB(ref samples);
                //string file = @"D://fft.txt";
                //FileStream fs_n = new FileStream(file, FileMode.Create);//新建文件
                //StreamWriter sw_n = new StreamWriter(fs_n, System.Text.Encoding.Default);
                //for (int i = 0; i < samples.Length; i++)
                //{
                //    sw_n.Write(samples[i]);
                //    sw_n.Write("\r\n");
                //    sw_n.Flush();
                //}
                //sw_n.Close();
                float[] temp_samples = new float[samples.Length];
                float[] temp_temp_samples = new float[samples.Length];
                //Array.Copy(samples, temp_samples, samples.Length);
                float[] freAmp = new float[2];
                Queue<float[]> bigAmp = new Queue<float[]>();
                float[][] bigAmpData = new float[5][];
                float[] popData = new float[3];
                if (c == 0)
                {
                    //五秒的FFT累加
                    if (FFTQueue.Count >= 5)
                    {
                        FFTQueue.Dequeue();
                        FFTQueue.Enqueue(samples);
                    }
                    else
                    {
                        FFTQueue.Enqueue(samples);
                    }
                    Console.WriteLine(FFTQueue.Count);
                    for (int o = 0; o < samples.Length; o++)
                    {
                        float now = new float();
                        for (int q = 0; q < FFTQueue.Count; q++)
                        {
                            now = now + FFTQueue.ElementAt(q)[o];
                        }
                        temp_samples[o] = now / FFTQueue.Count;
                    }
                    Array.Copy(temp_samples, temp_temp_samples, temp_samples.Length);
                    //第一通道画图
                    ///画矩形条
                    this.Focus();
                    y1.Clear();

                    //兼容解决谐波问题，取能量最大的五个，然后用最大的分别处以第2二到第4的，找到能整除的最小频率作为本次的频率
                    for (int j = 0; j < 5; j++)
                    {
                        if (j >= 3)
                        {
                            if (bigAmpData[0][1] % 8 == 0)
                            {
                                continue;
                            }
                        }
                        bigAmpData[j] = new float[3];
                        for (int i = 0; i < num; i++)//只显示需要的频率范围
                        {
                            if (y1_max < temp_temp_samples[i])
                            {
                                y1_max = temp_temp_samples[i];
                                bigAmpData[j][0] = i;
                                bigAmpData[j][1] = x[i];
                                bigAmpData[j][2] = y1_max;
                            }
                        }
                        bigAmp.Enqueue(bigAmpData[j]);
                        y1_max = 0;
                        temp_temp_samples[(int)bigAmpData[j][0]] = 0;
                    }
                    //首先设置本次频率和强度就是最大强度对应的频率
                    freAmp[0] = bigAmp.ElementAt(0)[1];
                    freAmp[1] = bigAmp.ElementAt(0)[2];

                    //判断如果最大五个强度中，可以整除最大强度的值中最小的对应的为本次频率。
                    /*
                     *(1)由于只有num个数据进行运算，因此大于(num/2)hz的频率不可做谐波处理，因为64虽然最大，但是即使取最大的三个，其他两个也一定是比小频率，如此不准确
                     *(2)计算谐波问题时，最大能量对应的是1hz时确定为1hz，谐波处理是将1hz刨除
                     **/
                    for (int i = bigAmp.Count - 1; i > 0; i--)
                    {
                        popData = bigAmp.ElementAt(i);
                        if ((bigAmp.ElementAt(0)[1] < num/2) && (bigAmp.ElementAt(0)[1] % popData[1] == 0) && (popData[1] < freAmp[0]) && (popData[0] != 0) && (popData[2] > freAmp[1] * 0.7))
                        {
                            freAmp[0] = popData[1];
                            freAmp[1] = popData[2];
                        }
                    }

                    bigAmp.Clear();//清空队列

                    //给图表添加数据
                    for (int i = 0; i < num; i++)//只取需要范围内的结果
                    {
                        y1.Add(temp_samples[i]);
                    }
                    y1_max = 0;

                    if (frequency1.Count == 5)
                    {
                        frequency1.Dequeue();//弹出第一个
                        frequency1.Enqueue(freAmp);//在末尾添加新的数据
                    }
                    else
                    {
                        frequency1.Enqueue(freAmp);//在末尾添加新的数据
                    }
                    float[] data_ca = new float[2];
                    data_ca = Droplet.DropFFT.Max_probability(frequency1);
                    label_frequency.Text = "频率：" + Math.Abs(data_ca[0]);
                    //label_amp.Text = "强度：" + caAmp;
                    label_amp.Text = "强度：" + data_ca[1];

                    amp1_json = SerializerHelper.JsonSerializer(y1);
                    amp1_flag = true;
                    zGraph1.f_Refresh();
                }
            }
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            flag = 0;
            //isConFlag = false;
            DspFunction.timeNow = DateTime.Now.ToString("yyyy年MM月dd日HH时mm分ss秒");
            DspFunction.fn = DspFunction.timeNow + ".wav";
            //DspFunction.ph = @"./spaceObject/" + DspFunction.fn;
            DspFunction.insertOriginDataFlag = 0;
            dspStatusLabel.Text = "暂停获取数据";
            button1.Enabled = true;
            button2.Enabled = false;
        }

        private void timer_run_time_Tick(object sender, EventArgs e)
        {
            run_time++;
            double d = Math.Floor(run_time / 86400);
            double h = Math.Floor((run_time - d * 86400) / 3600);
            double i = Math.Floor((run_time - h * 3600) / 60);
            double s = run_time - h * 3600 - i * 60;
            if (run_time <24*60*60)
                runTimeLabel.Text = d + "d" + " " + formatNum(h) + ":"+ formatNum(i) + ":" + formatNum(s);
        }

        private string formatNum(double num)
        {
            if (num < 10)
                return ("0" + num);
            else
                return num.ToString();
        }

        private void timerDrawZGraphAmp_Tick(object sender, EventArgs e)
        {
            if (oneDrawAmpFlag)
            {
                oneDrawAmpFlag = false;
                int n = 0;
                for (int i = 0; i < analogValues.Length / 1000; i++)
                {
                    if (i >= 1000)
                    {
                        break;
                    }
                    y_amp.Add((float)analogValues[i * 1000]);
                    n++;
                }
                for (int i = 0; i < n; i++)
                {
                    y_amp.RemoveAt(0);
                }
                zGraph2.f_Refresh();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(@".\spaceObject\0\");
        }

        private void deleteDataExpire()
        {
            while (true)
            {
                string path = @"./spaceObject/" + 0 + "/";//0是频道号，暂时写死，只操作0频道，因为其他的没存
                string[] filePathArr = Directory.GetFiles(path, "*.wav", SearchOption.TopDirectoryOnly);
                Dictionary<string, DateTime> fileCreateDate = new Dictionary<string, DateTime>();
                for (int i = 0; i < filePathArr.Length; i++)
                {
                    FileInfo fi = new FileInfo(filePathArr[i]);
                    fileCreateDate[filePathArr[i]] = fi.CreationTime;
                }
                fileCreateDate = fileCreateDate.OrderBy(f => f.Value).ToDictionary(f => f.Key, f => f.Value);
                foreach (KeyValuePair<string, DateTime> item in fileCreateDate)
                {
                    TimeSpan span1 = DateTime.Now - Convert.ToDateTime(item.Value);
                    if (span1.TotalDays > 10)
                    {
                        File.Delete(item.Key);//超过30天的删掉
                    }
                    //Console.WriteLine(item.Value + " -----> " + item.Key + "---->" + span1.TotalDays);
                }
                //File.Delete(fileCreateDate.First().Key);
                //Console.ReadKey();
                Thread.Sleep(86400000);//每天执行一次删除过期数据操作，其实也可以设置定时器
            }
        }
    }
}
